package com.gdou.crrp.service;

import com.gdou.crrp.entity.*;
import com.gdou.crrp.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommunityService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private TopicRepository topicRepository;

    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private CommentReplyRepository commentReplyRepository;

    @Autowired
    private ArticleCommentRepository articleCommentRepository;

    @Autowired
    private TopicCollectRepository topicCollectRepository;

    @Autowired
    private ArticleCollectRepository articleCollectRepository;


    //查找所有帖子
    public Page<Topic> showTopic(Pageable pageable){
        return topicRepository.findAll(pageable);
    }

    //通过帖子id查找某一帖子
    public Topic toTopic(Integer id){
        return topicRepository.getOne(id);
    }

    //查询所有帖子
//    public Page<String> findTopicTime(Pageable pageable){
//        Page<Topic> topicList =  topicRepository.findAll(pageable);
//        List<String> topictime = new ArrayList<>();
//        for (Topic topic : topicList){
//            Date date = topic.getTime();
//            String formatDate;
//            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            formatDate = dateFormat.format(date);
//            topictime.add(formatDate);
//        }
//        Page<String> topicTime = new PageImpl<>(topictime);
//        return topicTime;
//    }

    //保存帖子的信息
    public Topic saveTopic(String title, String content, int uid){
        Topic topic = new Topic();
        topic.setTitle(title);
        topic.setContent(content);
        topic.setTime(getTime());
        topic.setUid(uid);
        return topicRepository.save(topic);
    }

    //删除帖子
    public void deleteTopic(Integer id){
        topicRepository.deleteById(id);
    }

    //根据tid和uid删除收藏表
    public void deleteCollect(Integer tid, Integer uid){
        topicCollectRepository.deleteByTidAndUid(tid,uid);
    }

    //查找该帖子的所有评论
    public List<Comment> showComment(Integer id){
        return commentRepository.findAllByTid(id);
    }

    //查找该帖子的所有评论回复
    public List<CommentReply> showCommentReply(Integer tid){
        return commentReplyRepository.findAllByTid(tid);
    }

    //保存评论到数据库
    public Comment sendComment(Comment comment,Integer tid){
        comment.setTime(getTime());
        comment.setTid(tid);
        return commentRepository.save(comment);
    }

    //评论回复
    public CommentReply sendCommentReply(String comments,Integer cid,String name,Integer tid){
        CommentReply commentReply = new CommentReply();
        commentReply.setName(name);
        commentReply.setComments(comments);
        commentReply.setTid(tid);
        commentReply.setCid(cid);
        commentReply.setParentId(0);
        commentReply.setTime(getTime());
        return commentReplyRepository.save(commentReply);
    }

    //回复评论回复
    public CommentReply replyCommentReply(String comments,Integer cid,String name,Integer tid,Integer parentId,String replyName){
        CommentReply commentReply = new CommentReply();
        commentReply.setComments(comments);
        commentReply.setCid(cid);
        commentReply.setName(name);
        commentReply.setTid(tid);
        commentReply.setParentId(parentId);
        commentReply.setReplyName(replyName);
        commentReply.setName(name);
        commentReply.setTime(getTime());
        return commentReplyRepository.save(commentReply);
    }

    //通过uid查找用户
    public User findUser(Integer uid){
        return userRepository.getOne(uid);
    }

    //通过cid查找评论
    public Comment findComment(Integer cid){
        return commentRepository.getOne(cid);
    }

    //通过parentId查找评论回复
    public CommentReply findCommentReply(Integer parentId){
        return commentReplyRepository.getOne(parentId);
    }

    //通过标题查找所有符合的帖子
    public Page<Topic> findTopicByTitle(String title,Pageable pageable){
        Specification<Topic> spec = new Specification<Topic>() {
            @Override
            public Predicate toPredicate(Root<Topic> root,
                                         CriteriaQuery<?> criteriaQuery,
                                         CriteriaBuilder criteriaBuilder) {
                String keyTitle = splitString(title);
                return criteriaBuilder.like(root.get("title"),"%"+keyTitle+"%");
            }
        };
        Page<Topic> all = topicRepository.findAll(spec,pageable);
        return all;
    }

    //通过tid收藏帖子
    public TopicCollect collectTopic(Integer tid,Integer uid){
        TopicCollect topicCollect = new TopicCollect();
        topicCollect.setTid(tid);
        topicCollect.setUid(uid);
        topicCollect.setIs_collect(1);
        topicCollect.setTime(getTime());
        return topicCollectRepository.save(topicCollect);
    }

    //通过tid和uid查找特定的帖子
    public TopicCollect findByTidAndUid(Integer tid,Integer uid){
        return topicCollectRepository.findByTidAndUid(tid,uid);
    }

    //通过uid查找该用户收藏的帖子
    public List<TopicCollect> findCollectTopic(Integer uid){
        return topicCollectRepository.findAllByUid(uid);
    }

    /*
      查找所有收藏的帖子
      根据收藏表的tid搜索帖子表，并显示在个人中心页面
     */
    public List<Topic> showCollectTopic(){
        List<Topic> topicList = new ArrayList<>();
        List<TopicCollect> topicCollectList = topicCollectRepository.findAll();
        for (TopicCollect topic: topicCollectList) {
            Integer tid = topic.getTid();
            Topic topics = topicRepository.getOne(tid);
            topicList.add(topics);
        }
        return topicList;
    }

    /*
    ================================================================================================
    ================================================================================================
    -----------------------------          文章             ----------------------------------------
    ================================================================================================
    ================================================================================================
     */

    //保存文章的信息
    public Article saveArticle(Article article){
        article.setTime(getTime());
        return articleRepository.save(article);
    }

    //查找所有的文章
    public Page<Article> showArticle(Pageable pageable){
        return articleRepository.findAll(pageable);
    }

    //通过id查找某一文章
    public Article toArticle(Integer id){
        return articleRepository.getOne(id);
    }

    //保存评论到文章评论表
    public ArticleComment sendArticleComment(ArticleComment articleComment,Integer aid){
        articleComment.setTime(getTime());
        articleComment.setAid(aid);
        return articleCommentRepository.save(articleComment);
    }

    //查找该文章所有评论
    public List<ArticleComment> showArticleComment(Integer aid){
        return articleCommentRepository.findAllByAid(aid);
    }

    //
//    public Article saveCollectArticle(Article article){
//        if (article.getStatus() == 1){
//            article.setStatus(0);
//            topicCollectRepository.deleteByTidAndUid(article.getId(),article.getUid());
//        }else {
//            article.setStatus(1);
//        }
//        return articleRepository.save(article);
//    }

    //通过aid收藏文章
    public ArticleCollect collectArticle(Integer aid,Integer uid){
        ArticleCollect articleCollect = new ArticleCollect();
        articleCollect.setAid(aid);
        articleCollect.setUid(uid);
        articleCollect.setTime(getTime());
        return articleCollectRepository.save(articleCollect);
    }

    //通过uid查找该用户收藏的帖子
    public List<ArticleCollect> findCollectArticle(Integer uid)
    {
        return articleCollectRepository.findAllByUid(uid);
    }

    //通过uid和aid删除收藏表的数据
    public void deleteArticleCollect(Integer aid,Integer uid){
        articleCollectRepository.deleteByAidAndUid(aid,uid);
    }

    //通过aid和uid查找收藏表的数据
    public ArticleCollect findByAidAndUid(Integer aid,Integer uid){
        return articleCollectRepository.findByAidAndUid(aid, uid);
    }


    //通过标题查找所有符合的文章
    public Page<Article> findArticleByTitle(String title,Pageable pageable){
        Specification<Article> spec = new Specification<Article>() {
            @Override
            public Predicate toPredicate(Root<Article> root,
                                         CriteriaQuery<?> criteriaQuery,
                                         CriteriaBuilder criteriaBuilder) {
                String keyTitle = splitString(title);
                return criteriaBuilder.like(root.get("title"),"%"+keyTitle+"%");
            }
        };
        Page<Article> all = articleRepository.findAll(spec,pageable);
        return all;
    }

    /*
    ====================================================================================================
    ====================================================================================================
    -------------------------------          通用方法                  ---------------------------------
    ====================================================================================================
    ====================================================================================================
     */

    //拆分字符串，在每个字符后面加%
    public String splitString(String title){
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0;i<title.length();i++){
            if (stringBuffer.toString() != null && stringBuffer.toString() != ""){
                stringBuffer.append(",");
            }
            stringBuffer.append(title.charAt(i));
        }
        String keyTitle = stringBuffer.toString().substring(1);
        keyTitle = keyTitle.replace(",","%");
        return keyTitle;
    }

    public String getTime(){
        Date date = new Date();
        String formatDate;
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        formatDate = dateFormat.format(date);
        return formatDate;
    }
}

